package com.azarias.demo.register.client;

import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 本地注册缓存表，用以减少服务器之间通讯，避免每次调用都是远程
 * @author: Azarias_Jx
 * @date: 2022/1/4 10:21
 */
@Slf4j
public class ClientServiceRegistry {

    /**
     * 注册服务实例
     */
    RegisterClient registerClient;
    /**
     * 接口发送器
     */
    HttpSender httpSender;

    /**
     * 负责定时拉取注册表到客户端进行缓存的后台线程
     */
    private Daemon daemon;

    /**
     * 服务注册表拉取间隔时间
     */
    private static final Long SERVICE_REGISTRY_FETCH_INTERVAL = 30 * 1000L;

    /**
     * 客户端缓存的服务注册表
     */
    private Map<String, Map<String, ServiceInstance>> registry = new HashMap<String, Map<String, ServiceInstance>>();

    public ClientServiceRegistry(RegisterClient registerClient, HttpSender httpSender) {
        this.registerClient = registerClient;
        this.httpSender = httpSender;
        this.daemon = new Daemon();
        daemon.setDaemon(true);
    }

    public void initialize() {
        daemon.start();
    }

    public void destroy() {
        daemon.interrupt();
    }

    //后台守护线程，用以定时拉取注册表
    private class Daemon extends Thread{
        @Override
        public void run() {
            this.setName("Daemon");
            while (registerClient.isRunning()){
                try {
                    registry = httpSender.fetchServiceRegistry();
                    Thread.sleep(SERVICE_REGISTRY_FETCH_INTERVAL);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 获取服务注册表
     *
     * @return
     */
    public Map<String, Map<String, ServiceInstance>> getRegistry() {
        return registry;
    }
}
